package com.yunquan.ohana.utils

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import java.io.File


/**
 * android安装应用(适用于各个版本)$
 *
 * @author yjp
 * @date 2021-08-03 1:46
 */
class InstallUtils(
    private val mAct: Activity, //下载下来后文件的路径
    private val mPath: String
) {
    fun install() {
        val authority = "${mAct.packageName}.provider"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startInstallO(authority)
        } else {
            startInstallN(authority)
        }
    }

    /**
     * android1.x-6.x
     */
    private fun startInstall() {
        val install = Intent(Intent.ACTION_VIEW)
        install.setDataAndType(
            Uri.parse("file://$mPath"),
            "application/vnd.android.package-archive"
        )
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        mAct.startActivity(install)
    }

    /**
     * android7.x
     * @param authority "[包名].provider"
     */
    private fun startInstallN(authority: String) {
        //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
        val apkUri: Uri = FileProvider.getUriForFile(mAct, authority, File(mPath))
        val install = Intent(Intent.ACTION_VIEW)
        //由于没有在Activity环境下启动Activity,设置下面的标签
        install.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        install.setDataAndType(apkUri, "application/vnd.android.package-archive")
        mAct.startActivity(install)
    }

    /**
     * android8.x
     * @param authority "[包名].provider"
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun startInstallO(authority: String) {
        val isGranted = mAct.packageManager.canRequestPackageInstalls()
        if (isGranted) startInstallN(authority) //安装应用的逻辑(写自己的就可以)
        else AlertDialog.Builder(mAct)
            .setCancelable(false)
            .setTitle("安装应用需要打开未知来源权限，请去设置中开启权限")
            .setPositiveButton("确定") { _, _ ->
                val intent = Intent(ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                mAct.startActivityForResult(intent, UNKNOWN_CODE)
            }
            .show()
    }

    companion object {
        var UNKNOWN_CODE = 2018
    }
}